package com.zklh.leetcode.top100.problem102;

import com.zklh.leetcode.tree.model.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 层序遍历算法
 */
public class Solution1 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> currentQueue = new LinkedList<>();
        Queue<TreeNode> nextFloorQueue = new LinkedList<>();
        Queue<TreeNode> tempQueue = null;
        List<List<Integer>> levelValues = new LinkedList<>();
        if (root == null) {
            return levelValues;
        }
        TreeNode pointer = null;
        currentQueue.add(root);
        while (!currentQueue.isEmpty()) {
            List<Integer> floorValues = new LinkedList<>();
            while (!currentQueue.isEmpty()) {
                pointer = currentQueue.poll();
                floorValues.add(pointer.val);
                if (pointer.left != null) {
                    nextFloorQueue.add(pointer.left);
                }
                if (pointer.right != null) {
                    nextFloorQueue.add(pointer.right);
                }
            }
            levelValues.add(floorValues);
            tempQueue = currentQueue;
            currentQueue = nextFloorQueue;
            nextFloorQueue = tempQueue;
        }
        return levelValues;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        Solution1 solution = new Solution1();
        System.out.println(solution.levelOrder(root));
    }
}
